package gdut.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;


import java.util.concurrent.TimeUnit;

@Slf4j
public class RedisUtils {
    private StringRedisTemplate stringRedisTemplate;

    private static final String PREFIX_DEFAULT="default";
    private static final String REDIS_SPLIT = ":";

    public RedisUtils(StringRedisTemplate stringRedisTemplate){
        this.stringRedisTemplate=stringRedisTemplate;
    }

    public String get(String key){
        //验证key存不存在
        if(!checkKey(key)){
            return null;
        }
        try {
            return key==null?null:stringRedisTemplate.opsForValue().get(key);
        }catch (Exception e){
            log.error("redis get error,key:{}",key);
            return null;
        }
    }
    public boolean checkKey(String key){
        if(key==null){
            return false;
        }
        try{
            return stringRedisTemplate.hasKey(key);
        }catch (Exception e){
            log.error("redis checkKey error,key:{}",key);
            return false;
        }
    }

    public boolean set(String key,String value){
        //判断key和value合不合法
        if(key==null || value==null){
            return false;
        }
        try {
            stringRedisTemplate.opsForValue().set(key,value);
            return true;
        }catch (Exception e){
            log.error("redis set error,key:{},value:{}",key,value);
            return false;
        }
    }

    public boolean set(String key, String value, long timeout){
        try {
            if(key==null || value==null){
                return false;
            }
            if (timeout>0){
                stringRedisTemplate.opsForValue().set(key, value, timeout, TimeUnit.SECONDS);
            }else {
                set(key, value);
            }
            return true;
        }catch (Exception e){
            log.error("redis set error, key:{}, value:{}", key, value);
            return false;
        }
    }

    public String buildKey(String prefix, String... args){
        if(prefix==null){
            //使用一个默认前缀
            prefix=PREFIX_DEFAULT;
        }
        StringBuilder builder=new StringBuilder();
        builder.append(prefix);
        if(args!=null){
            for(String arg:args){
                builder.append(REDIS_SPLIT).append(arg);
            }
        }
        return builder.toString();
    }
}